package com.yc.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yc.domain.JsonModel;
import com.yc.domain.MyPageBean;
import com.yc.domain.Resfood;
import com.yc.domain.ResfoodVO;
import com.yc.service.FileService;
import com.yc.service.ResfoodBiz;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@RestController
@RequestMapping("/resfood")
@Tag(name = "菜品API",description = "菜品管理相关的接口")
public class ResfoodController {
    @Autowired
    ResfoodBiz resfoodBiz;
    @Autowired
    FileService fileService;

    @GetMapping("findById/{fid}")
    public JsonModel findById(@PathVariable Integer fid) {

        try {
            Resfood foods = resfoodBiz.findById(fid);
          return JsonModel.ok().setData(foods);
        } catch (Exception e) {
            return JsonModel.err("失败");
        }

    }
    @GetMapping("/findAll")
    public JsonModel findAll() {

        try {
            List<Resfood> foods = resfoodBiz.findAll();
            return JsonModel.ok().setData(foods);
        } catch (Exception e) {
            return JsonModel.err("失败");
        }
    }
    @Operation(summary = "分页查询",description = "分页查询菜品信息")
    @ApiResponse(responseCode = "200",description = "分页查询菜品信息成功",
    content=@Content(mediaType = "application/json",
            schema = @Schema(implementation = MyPageBean.class)))
    @PostMapping("/findByPage")
    public JsonModel findByPage(@RequestBody MyPageBean page){

        try {
            MyPageBean pageInfo = resfoodBiz.findByPage(page);
            return JsonModel.ok().setData(pageInfo);
        } catch (Exception e) {
            return JsonModel.err();
        }
    }
    @PostMapping("/addResfood")
    public JsonModel addResfood(@ModelAttribute ResfoodVO resfoodVO) throws ExecutionException, InterruptedException {

        CompletableFuture<String> fileUrlFuture = fileService.upload(resfoodVO.getFphotofile());
        String fphotoFilePath = fileUrlFuture.get();
        Resfood resfood = new Resfood();
        BeanUtils.copyProperties(resfoodVO,resfood);
        resfood.setFphoto(fphotoFilePath);
        int fid = resfoodBiz.addResfood(resfood);
        resfoodVO.setFid(fid);
        resfoodVO.setFphoto(fphotoFilePath);
       return JsonModel.ok().setData(resfoodVO);
    }
}
